import axios, { AxiosRequestConfig } from "axios";
// 引入配置文件
import requstConfig from "./request.config";

// 获取语言编码
const getLanguageCode = () => {
  const loanguageCode =
    localStorage.getItem("languageCode") || navigator.language || "en_US";
  return loanguageCode.replace("_", "-");
};

// 获取地址
const getRootAddress = () => {
  const rootAddress =
    localStorage.getItem("rootAddress") || requstConfig.rootAddress;
  return rootAddress;
};

// 获取上传路径
const getUploadAddress = () => {
  const uploadAddress =
    localStorage.getItem("uploadAddress") || requstConfig.uploadAddress;
  return uploadAddress;
};

// 创建axios实例
const requestAxios = axios.create({
  baseURL: requstConfig.rootAddress,
  timeout: 5000, // 请求超时时间
  headers: {
    token: sessionStorage.getItem(requstConfig.tokenStroageKey),
    languageCode: getLanguageCode(),
  },
});

// request拦截器
requestAxios.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    return config;
  },
  (error) => {
    // 请求超时
    if (
      error.code === "ECONNABORTED" &&
      error.message.indexOf("timeout") !== -1
    ) {
      console.log("timeout请求超时");
    }
  }
);

const request = (param: any) => {
  return requestAxios({
    ...param,
    headers: {
      token: localStorage.getItem(requstConfig.tokenStroageKey),
      languageCode: getLanguageCode(),
      contentType: "application/json;charset=UTF-8",
      ...param.headers,
    },
  });
};

// 创建upload的axios实例
const requestAxiosUpload = axios.create({
  baseURL: requstConfig.uploadAddress,
  timeout: 5000, // 请求超时时间
  headers: {
    token: sessionStorage.getItem(requstConfig.tokenStroageKey),
    languageCode: getLanguageCode(),
    "Content-Type": "multipart/form-data",
  },
});

const upload = (param: any) => {
  return requestAxiosUpload({
    url: "/file/upload",
    method: "post",
    type: "multipart/form-data",
    ...param,
    headers: {
      token: localStorage.getItem(requstConfig.tokenStroageKey),
      languageCode: getLanguageCode(),
      "Content-Type": "multipart/form-data",
      ...param.headers,
    },
  });
};

const setToken = (token: string) => {
  localStorage.setItem(requstConfig.tokenStroageKey, token);
};

const getToken = () => {
  return localStorage.getItem(requstConfig.tokenStroageKey);
};

export default {
  request,
  upload,
  setToken,
  getToken,
  getRootAddress,
  getUploadAddress,
};
